package com.example.controller;


import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.example.annotation.Log;
import com.example.common.result.Result;
import com.example.entity.activiti.TaskInfo;
import com.example.entity.dto.CopteAddDto;
import com.example.entity.dto.FileUpload.FileListDto;
import com.example.entity.dto.SaleOrder.CoptcCopy;
import com.example.entity.vo.Business.CoptcPlus;
import com.example.entity.vo.CoptcVo;
import com.example.entity.vo.CoptfVo;
import com.example.entity.yifei.*;
import com.example.entity.ymlConfig.YmlConfig;
import com.example.exception.CustomException;
import com.example.mapper.*;
import com.example.service.CoptcService;
import com.example.service.CopteService;
import com.example.service.FileService;
import com.example.service.impl.ActFlowCommService;
import com.example.untils.BeanUtils;
import com.example.untils.SecurityUtils;
import com.example.untils.StringUtils;
import com.example.untils.TimeUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author LiangPandeng
 * @since 2024-05-30
 */
@RestController
@Api(tags = "销售订单变更单")
@Slf4j
@RequestMapping("/api/copte")
public class CopteController {
    @Autowired
    private FileService fileService;
    @Resource
    private CoptcMapper coptcMapper;
    @Resource
    private ActFlowCommService actFlowCommService;
    @Resource
    private CopteService copteService;
    @Resource
    private CopteMapper copteMapper;
    @Resource
    private CoptfMapper coptfMapper;

    @Resource
    private CoptcService coptcService;

    @Resource
    private CopmgMapper copmgMapper;

    @Resource
    private CoptdMapper coptdMapper;

    @ApiOperation("客户订单已审核列表")
    @PostMapping("/list")
    public Result<PageInfo<List<CoptcCopy>>> list(@RequestBody CoptcCopy dto) {
        PageHelper.startPage(dto.getPageNum(), dto.getPageSize());
        List<CoptcCopy> list = copteMapper.getList(dto);
        PageInfo<List<CoptcCopy>> pageInfo = new PageInfo(list);
        return Result.success(pageInfo);
    }

    @ApiOperation("新增客户订单变更单")
    @PostMapping("/add")
    @DSTransactional
    public Result add(@RequestBody CopteAddDto dto) {
        Copte copte = new Copte();
        BeanUtils.copyPropertiesIgnoreCase(dto.getDt(), copte);
        copte.setCompany(YmlConfig.getYFCOMPANY());
        copte.setCreateDate(TimeUtils.getNowTime());
        copte.setCreator(SecurityUtils.getLoginUser().getUsername());
        copte.setTEI03(new BigDecimal(copte.getTEI03()).setScale(2, RoundingMode.HALF_UP).doubleValue());
        copte.setTEI04(new BigDecimal(copte.getTEI04()).setScale(2, RoundingMode.HALF_UP).doubleValue());

        if(StringUtils.isEmpty(dto.getDt().getTE003())) {   // 如果没有版本号，就是新增
            Integer version = copteMapper.getCopteVersion(copte.getTE001(), copte.getTE002());
            copte.setTE003(String.format("%04d", version));
            copteMapper.insert(copte);
            for(Coptf coptf : dto.getDs()) {
                coptf.setCOMPANY(YmlConfig.getYFCOMPANY());
                coptf.setCREATE_DATE(TimeUtils.getNowTime());
                coptf.setCREATOR(SecurityUtils.getLoginUser().getUsername());
                coptf.setTF003(copte.getTE003());
                coptfMapper.insert(coptf);
            }
        }else{  // 否则是修改
            copteMapper.update(copte, new LambdaQueryWrapper<Copte>().eq(Copte::getTE001, copte.getTE001()).eq(Copte::getTE002, copte.getTE002()).eq(Copte::getTE003, copte.getTE003()));
            List<Coptf> coptfList = coptfMapper.selectList(new LambdaQueryWrapper<Coptf>().eq(Coptf::getTF001, copte.getTE001()).eq(Coptf::getTF002, copte.getTE002()).eq(Coptf::getTF003, copte.getTE003()));
            for(Coptf f : dto.getDs()) {
                Boolean flag = false;
                for(Coptf coptf : coptfList) {
                    if(coptf.getTF104().trim().equals(f.getTF104().trim())) {
                        flag = true; break;
                    }
                }
                if(flag == false) {  // 进来的在数据库中不存在，则是新增
                    f.setCOMPANY(YmlConfig.getYFCOMPANY());
                     f.setCREATE_DATE(TimeUtils.getNowTime());
                    f.setCREATOR(SecurityUtils.getLoginUser().getUsername());
                    Integer xh = coptfMapper.getTF004(f.getTF001(), f.getTF002(), f.getTF003());
                    f.setTF004(String.format("%04d", xh));
                    coptfMapper.insert(f);
                }
            }
            for(Coptf coptf : coptfList) {
                Boolean flag = false;
                Coptf ttt = null;
                for(Coptf f : dto.getDs()) {
                    if(coptf.getTF104().trim().equals(f.getTF104().trim())) {
                        flag = true; ttt = f;  break;
                    }
                }
                if(flag) {
                    Integer count = coptfMapper.selectCount(new LambdaQueryWrapper<Coptf>().eq(Coptf::getTF001, copte.getTE001()).eq(Coptf::getTF002, copte.getTE002()).eq(Coptf::getTF003, copte.getTE003()).eq(Coptf::getTF104, coptf.getTF104()));
                    if(count > 1) {
                        throw new CustomException("500", "无法更新,存在多行一样的TF104");
                    }
                    coptfMapper.update(ttt, new LambdaQueryWrapper<Coptf>().eq(Coptf::getTF001, copte.getTE001()).eq(Coptf::getTF002, copte.getTE002()).eq(Coptf::getTF003, copte.getTE003()).eq(Coptf::getTF104, coptf.getTF104()));
                }else{  // 如果数据库中有，但是传进来的没有。就是删除
                    Integer count = coptfMapper.selectCount(new LambdaQueryWrapper<Coptf>().eq(Coptf::getTF001, copte.getTE001()).eq(Coptf::getTF002, copte.getTE002()).eq(Coptf::getTF003, copte.getTE003()).eq(Coptf::getTF104, coptf.getTF104()));
                    if(count > 1) {
                        throw new CustomException("500", "无法删除,存在多行一样的TF104");
                    }
                    coptfMapper.delete(new LambdaQueryWrapper<Coptf>().eq(Coptf::getTF001, copte.getTE001()).eq(Coptf::getTF002, copte.getTE002()).eq(Coptf::getTF003, copte.getTE003()).eq(Coptf::getTF104, coptf.getTF104()));
                }
            }
            // 修改
            // 新增
            // 删除
        }
        return Result.success("保存成功");
    }


    @ApiOperation("客户订单变更单详情(旧数据的对比)")
    @PostMapping("/changeDetailOld/{db}/{dh}/{version}")
    public Result<CoptcVo> changeDetailOld(@PathVariable String db, @PathVariable String dh, @PathVariable String version) {
        Copte copte = copteMapper.selectOne(new LambdaQueryWrapper<Copte>().eq(Copte::getTE001, db).eq(Copte::getTE002, dh).eq(Copte::getTE003, version));
        List<Coptf> coptfList = coptfMapper.selectList(new LambdaQueryWrapper<Coptf>().eq(Coptf::getTF001, db).eq(Coptf::getTF002, dh).eq(Coptf::getTF003, version));

        CoptcPlus coptcPlus = coptcMapper.copteCoptcPlus(db, dh, copte.getTE007(), copte.getTE008(), copte.getTE009(),
                copte.getTE041(), copte.getTE065());
        if (coptcPlus.getREMARK()!=null){
            coptcPlus.setTc015(coptcPlus.getREMARK());
        }
        coptcPlus.setVersion(version);
        coptcPlus.setChangeReason(copte.getTE006());
        if(copte != null) coptcPlus.setChangeReason(copte.getTE006());
        coptcPlus.setTc004(copte.getTE107());
        coptcPlus.setTc005(copte.getTE108());
        coptcPlus.setTc006(copte.getTE109());
        coptcPlus.setTc007(copte.getTE110());
        coptcPlus.setTc008(copte.getTE111());
        coptcPlus.setTc009(copte.getTE112());
        coptcPlus.setTc010(copte.getTE113());
        coptcPlus.setTc011(copte.getTE114());
        coptcPlus.setTc012(copte.getTE115());
        coptcPlus.setTc013(copte.getTE116());
        coptcPlus.setTc014(copte.getTE117());
        coptcPlus.setREMARK(copte.getTE152());  // 备注
        coptcPlus.setTc016(copte.getTE118());
        coptcPlus.setTc017(copte.getTE119());
        coptcPlus.setTc018(copte.getTE120());
        coptcPlus.setTc019(copte.getTE121());
        coptcPlus.setTc020(copte.getTE122());
        coptcPlus.setTc021(copte.getTE123());
        coptcPlus.setTc022(copte.getTE124());
        coptcPlus.setTc023(copte.getTE125());
        coptcPlus.setTc024(copte.getTE126());
        coptcPlus.setTc025(copte.getTE127());
        coptcPlus.setTc026(copte.getTE128());

//        coptcPlus.setTc029(copte.getTEI03());
//        coptcPlus.setTc030(copte.getTEI04());
//        coptcPlus.setTc031();  // 数量

        coptcPlus.setTc032(copte.getTE129());
        coptcPlus.setTc033(copte.getTE130());
        coptcPlus.setTc034(copte.getTE131());
        coptcPlus.setTc035(copte.getTE132());
        coptcPlus.setTc036(copte.getTE133());
        coptcPlus.setTc037(copte.getTE134());
        coptcPlus.setTc038(copte.getTE135());
//        coptcPlus.setTc039(copte.getTE038());
//        coptcPlus.setTc040(copte.getTE039());
        coptcPlus.setTc041(copte.getTE136());
        coptcPlus.setTc042(copte.getTE137());

        coptcPlus.setTc045(copte.getTE138());
        coptcPlus.setTc047(copte.getTE139());
//        coptcPlus.setTc048(copte.getTE044());
//        coptcPlus.setTc050(copte.getTE045());
        coptcPlus.setTc052(copte.getTE153());
        coptcPlus.setTc053(copte.getTE154());
        coptcPlus.setTc054(copte.getTE155());
        coptcPlus.setTc055(copte.getTE156());
        coptcPlus.setTc056(copte.getTE143());
        coptcPlus.setTc057(copte.getTE144());

        coptcPlus.setTc073(copte.getTE158());
        coptcPlus.setTc074(copte.getTE159());
        coptcPlus.setTc075(copte.getTE160());

        coptcPlus.setTc077(copte.getTE162());
        coptcPlus.setTc003(copte.getUDF02());
        coptcPlus.setTci01(copte.getUDF08());  // 客户合同交期
        coptcPlus.setTci02(copte.getUDF04());  // 客户订单日期
        coptcPlus.setUdf02(copte.getUDF06());
        coptcPlus.setUdf06(copte.getUDF10());  // 客户收货地址编号
        coptcPlus.setUdf01(copte.getUDF12());  // 供应链采购单号
        coptcPlus.setUdf04(copte.getTE048());
//        coptcPlus.setUdf51(copte.getUDF51());
//        coptcPlus.setUdf52(copte.getUDF53());
//        coptcPlus.setUdf53(copte.getUDF55());
        List<Attach> fileList = fileService.fileList(new FileListDto(db, dh, "COPI06", YmlConfig.getYFCOMPANY()));
        List<String> urls = new ArrayList<>();
        for(int i = 0; i < fileList.size(); i++) {
            String docId = fileList.get(i).getDocid();
            String fileName = fileList.get(i).getFilename();
            String url = "/files/" + docId.substring(3, 6) + "000" +
                    "/" + docId + "/" + fileName;
            urls.add(url);
        }
        List<Coptd> coptdPlusList = coptdMapper.getCoptdPlusList(db, dh);
        for(Coptd coptd : coptdPlusList) {   // 新增的不会出现在这里
            Coptf coptfCp = null;
            for(Coptf coptf : coptfList) {
                if((coptf.getTF054().trim().equals("2") || coptf.getTF054().trim().equals("3")) && coptf.getTF104().trim().equals(coptd.getTd003().trim())) {
                    coptfCp = coptf;
                    break;
                }
            }
            if(coptfCp == null) continue;
            coptd.setChangeType(coptfCp.getTF054());
            coptd.setChangeReason(coptfCp.getTF018());
            coptd.setModiDate(coptfCp.getMODI_DATE());
            coptd.setModifier(coptfCp.getMODIFIER());
            coptd.setTd004(coptfCp.getTF105());
            coptd.setTd005(coptfCp.getTF106());
            coptd.setTd006(coptfCp.getTF107());
            coptd.setTd007(coptfCp.getTF108());
            coptd.setTd008(coptfCp.getTF109());

            coptd.setTd010(coptfCp.getTF110());
            coptd.setTd011(coptfCp.getTF113());
            coptd.setTd012(coptfCp.getTF114());
            coptd.setTd013(coptfCp.getTF115());
            coptd.setTd014(coptfCp.getTF116());
            coptd.setTd015(coptfCp.getTF142());
            coptd.setTd020(coptfCp.getTF139());
            coptd.setTd022(coptfCp.getTF111());
            coptd.setTd023(coptfCp.getTF112());
            coptd.setTd024(coptfCp.getTF120());
            coptd.setTd026(coptfCp.getTF121());
            coptd.setTd027(coptfCp.getTF122());
            coptd.setTd029(coptfCp.getTF125());
            coptd.setTd030(coptfCp.getTF126());
            coptd.setTd031(coptfCp.getTF127());
            coptd.setTd032(coptfCp.getTF128());
            coptd.setTd034(coptfCp.getTF129());
            coptd.setTd036(coptfCp.getTF132());
            coptd.setTd037(coptfCp.getTF133());  // 税率
            coptd.setTd038(coptfCp.getTF134());
            coptd.setTd039(coptfCp.getTF135());

            coptd.setTdi01(coptfCp.getTFI11());
            coptd.setTdi02(coptfCp.getTFI12());
            coptd.setTdi03(coptfCp.getTFI13());
            coptd.setTd061(coptfCp.getTF153());
            coptd.setTd062(coptfCp.getTF154());
            coptd.setUdf03(coptfCp.getUDF05());  // 生管确认日
            coptd.setUdf04(coptfCp.getUDF01());  // 客户品名
            coptd.setUdf05(coptfCp.getUDF03());  // 客户品号规格

            coptd.setUdf51(coptfCp.getUDF52());  // 总金额(六位数)
            coptd.setUdf52(coptfCp.getUDF54());
            coptd.setUdf53(coptfCp.getUDF56());

            coptd.setUdf54(coptfCp.getUDF58());  // 总金额(六位数)
            coptd.setUdf55(coptfCp.getUDF60());
            coptd.setUdf56(coptfCp.getUDF62());
            if(coptfCp.getTF054().equals("3")) coptd.setTd016(coptfCp.getTF017());

            Coptd dd = coptdMapper.coptfCoptdPlus(coptd.getTd007(), coptd.getTd004());
            coptd.setMC002(dd.getMC002());
            coptd.setMb064(dd.getMb064());
        }

        for(Coptf coptf : coptfList) {     // 变更单中新增的
            if(coptf.getTF054().equals("1")) {
                Coptd coptd = new Coptd();
                coptd.setChangeType("1");
                coptd.setChangeReason(coptf.getTF018());
                coptd.setCreator(coptf.getCREATOR());
                coptd.setTd001(db); coptd.setTd002(dh); coptd.setTd003(coptf.getTF104());
                coptd.setTd004(coptf.getTF105());
                coptd.setTd005(coptf.getTF106());
                coptd.setTd006(coptf.getTF107());
                coptd.setTd007(coptf.getTF108());
                coptd.setTd008(coptf.getTF109());

                coptd.setTd010(coptf.getTF110());
                coptd.setTd011(coptf.getTF113());
                coptd.setTd012(coptf.getTF114());
                coptd.setTd013(coptf.getTF115());
                coptd.setTd014(coptf.getTF116());
                coptd.setTd015(coptf.getTF142());
                coptd.setTd020(coptf.getTF139());
                coptd.setTd022(coptf.getTF111());
                coptd.setTd023(coptf.getTF112());
                coptd.setTd024(coptf.getTF120());
                coptd.setTd026(coptf.getTF121());
                coptd.setTd027(coptf.getTF122());
                coptd.setTd029(coptf.getTF125());
                coptd.setTd030(coptf.getTF126());
                coptd.setTd031(coptf.getTF127());
                coptd.setTd032(coptf.getTF128());
                coptd.setTd034(coptf.getTF129());
                coptd.setTd036(coptf.getTF132());
                coptd.setTd037(coptf.getTF133());  // 税率
                coptd.setTd038(coptf.getTF134());
                coptd.setTd039(coptf.getTF135());

                coptd.setTdi01(coptf.getTFI11());
                coptd.setTdi02(coptf.getTFI12());
                coptd.setTdi03(coptf.getTFI13());
                coptd.setTd061(coptf.getTF153());
                coptd.setTd062(coptf.getTF154());
                coptd.setUdf03(coptf.getUDF05());  // 生管确认日
                coptd.setUdf04(coptf.getUDF01());  // 客户品名
                coptd.setUdf05(coptf.getUDF03());  // 客户品号规格

                coptd.setUdf51(coptf.getUDF52());  // 总金额(六位数)
                coptd.setUdf52(coptf.getUDF54());
                coptd.setUdf53(coptf.getUDF56());

                coptd.setUdf54(coptf.getUDF58());  // 总金额(六位数)
                coptd.setUdf55(coptf.getUDF60());
                coptd.setUdf56(coptf.getUDF62());

                Coptd dd = coptdMapper.coptfCoptdPlus(coptd.getTd007(), coptd.getTd004());
                coptd.setMC002(dd.getMC002());
                coptd.setMb064(dd.getMb064());

                coptd.setApchnum(0D);
                coptd.setSjchnum(0D);
                coptd.setThnum(0D);
                coptd.setBhnum(0D);
                coptdPlusList.add(coptd);
            }
        }

        BigDecimal tc029 = new BigDecimal(0);
        BigDecimal tc030 = new BigDecimal(0);
        BigDecimal tc031 = new BigDecimal(0);
        BigDecimal tci03 = new BigDecimal(0);
        BigDecimal tci04 = new BigDecimal(0);
        BigDecimal udf51 = new BigDecimal(0);
        BigDecimal udf52 = new BigDecimal(0);
        BigDecimal udf53 = new BigDecimal(0);
        for(Coptd coptd : coptdPlusList) {
            tc029 = tc029.add(new BigDecimal(coptd.getTd038().toString()));
            tc030 = tc030.add(new BigDecimal(coptd.getTd039().toString()));
            tci03 = tci03.add(new BigDecimal(coptd.getTdi01().toString()));
            tci04 = tci04.add(new BigDecimal(coptd.getTdi02().toString()));
            tc031 = tc031.add(new BigDecimal(coptd.getTd008().toString()));
            udf51 = udf51.add(new BigDecimal(coptd.getUdf51().toString()));
            udf52 = udf52.add(new BigDecimal(coptd.getUdf52().toString()));
            udf53 = udf53.add(new BigDecimal(coptd.getUdf53().toString()));
        }
        coptcPlus.setTc029(tc029.doubleValue());  // 税前金额
        coptcPlus.setTc030(tc030.doubleValue());  // 税额
        coptcPlus.setTc031(tc031.doubleValue());   // 数量
        coptcPlus.setTci03(tci03.doubleValue());  // 本币税前金额
        coptcPlus.setTci04(tci04.doubleValue());  // 本币税额
        coptcPlus.setUdf51(udf51.doubleValue());  // 总金额（六位数的）
        coptcPlus.setUdf52(udf52.doubleValue());  // 自定义税前金额（六位数的）
        coptcPlus.setUdf53(udf53.doubleValue());  // 自定义税额（四位数的）

        if(!coptdPlusList.isEmpty()){
            coptdPlusList.stream().forEach(arr -> {
                arr.setTd012(arr.getUdf51());
                if (arr.getMg005()==null||arr.getMg005().equals("")){
                    List<Copmg> copmgs = copmgMapper.selectList(new LambdaQueryWrapper<Copmg>()
                            .eq(Copmg::getMg001, coptcPlus.getTc004()).eq(Copmg::getMg003, arr.getTd014()).eq(Copmg::getMg002,arr.getTd004()));
                    if (!copmgs.isEmpty()){
                        arr.setMg005(copmgs.get(0).getMg005());
                        arr.setMg006(copmgs.get(0).getMg006());
                    }
                }
                Double td010Double = this.coptdMapper.getTd010Double(coptcPlus.getTc004(), arr.getTd004());
                if (td010Double!=null){
                    if (arr.getTd011()>td010Double){
                        arr.setHistoricalunitprice(2);
                    }else if (arr.getTd011().equals(td010Double)){
                        arr.setHistoricalunitprice(1);
                    }else {
                        arr.setHistoricalunitprice(0);
                    }
                }
            });
        }

        CoptcVo coptcVo =new CoptcVo();
        coptcVo.setCoptc(coptcPlus);
        coptcVo.setCoptdList(coptdPlusList);
        coptcVo.setUrls(urls);
        return Result.success(coptcVo);
    }

    @ApiOperation("客户订单变更单详情(把变更单中的格式转换为销售订单)")
    @PostMapping("/changeDetail/{db}/{dh}/{version}")
    public Result<CoptcVo> changeDetail(@PathVariable String db, @PathVariable String dh, @PathVariable String version) {
        Copte copte = copteMapper.selectOne(new LambdaQueryWrapper<Copte>().eq(Copte::getTE001, db).eq(Copte::getTE002, dh).eq(Copte::getTE003, version));
        List<Coptf> coptfList = coptfMapper.selectList(new LambdaQueryWrapper<Coptf>().eq(Coptf::getTF001, db).eq(Coptf::getTF002, dh).eq(Coptf::getTF003, version));

        CoptcPlus coptcPlus = coptcMapper.copteCoptcPlus(db, dh, copte.getTE007(), copte.getTE008(), copte.getTE009(),
                copte.getTE041(), copte.getTE065());
        if (coptcPlus.getREMARK()!=null){
            coptcPlus.setTc015(coptcPlus.getREMARK());
        }
        coptcPlus.setVersion(version);
        coptcPlus.setChangeReason(copte.getTE006());
        if(copte != null) coptcPlus.setChangeReason(copte.getTE006());
        coptcPlus.setTc004(copte.getTE007());
        coptcPlus.setTc005(copte.getTE008());
        coptcPlus.setTc006(copte.getTE009());
        coptcPlus.setTc007(copte.getTE010());
        coptcPlus.setTc008(copte.getTE011());
        coptcPlus.setTc009(copte.getTE012());
        coptcPlus.setTc010(copte.getTE013());
        coptcPlus.setTc011(copte.getTE014());
        coptcPlus.setTc012(copte.getTE015());
        coptcPlus.setTc013(copte.getTE016());
        coptcPlus.setTc014(copte.getTE017());
        coptcPlus.setREMARK(copte.getTE052());  // 备注
        coptcPlus.setTc016(copte.getTE018());
        coptcPlus.setTc017(copte.getTE019());
        coptcPlus.setTc018(copte.getTE020());
        coptcPlus.setTc019(copte.getTE021());
        coptcPlus.setTc020(copte.getTE022());
        coptcPlus.setTc021(copte.getTE023());
        coptcPlus.setTc022(copte.getTE024());
        coptcPlus.setTc023(copte.getTE025());
        coptcPlus.setTc024(copte.getTE026());
        coptcPlus.setTc025(copte.getTE027());
        coptcPlus.setTc026(copte.getTE028());
        coptcPlus.setTc027(copte.getTE029());   // 变更单的审核码
        coptcPlus.setTc028(copte.getTE030());

//        coptcPlus.setTc029(copte.getTEI03());
//        coptcPlus.setTc030(copte.getTEI04());
//        coptcPlus.setTc031();  // 数量

        coptcPlus.setTc032(copte.getTE031());
        coptcPlus.setTc033(copte.getTE032());
        coptcPlus.setTc034(copte.getTE033());
        coptcPlus.setTc035(copte.getTE034());
        coptcPlus.setTc036(copte.getTE035());
        coptcPlus.setTc037(copte.getTE036());
        coptcPlus.setTc038(copte.getTE037());
//        coptcPlus.setTc039(copte.getTE038());
        coptcPlus.setTc040(copte.getTE039());
        coptcPlus.setTc041(copte.getTE040());
        coptcPlus.setTc042(copte.getTE041());
        coptcPlus.setTc045(copte.getTE042());
        coptcPlus.setTc047(copte.getTE043());
        coptcPlus.setTc048(copte.getTE044());
        coptcPlus.setTc050(copte.getTE045());
        coptcPlus.setTc052(copte.getTE053());
        coptcPlus.setTc053(copte.getTE054());
        coptcPlus.setTc054(copte.getTE055());
        coptcPlus.setTc055(copte.getTE056());
        coptcPlus.setTc056(copte.getTE141());
        coptcPlus.setTc057(copte.getTE142());
        coptcPlus.setTc073(copte.getTE061());
        coptcPlus.setTc074(copte.getTE062());
        coptcPlus.setTc075(copte.getTE063());
        coptcPlus.setTc077(copte.getTE065());
        coptcPlus.setTc003(copte.getUDF01());  // 新订单日期
        coptcPlus.setTci01(copte.getUDF07());  // 客户合同交期
        coptcPlus.setTci02(copte.getUDF03());  // 客户订单日期
        coptcPlus.setUdf02(copte.getUDF05());  // 新交易条件
        coptcPlus.setUdf06(copte.getUDF09());  // 客户收货地址编号
        coptcPlus.setUdf01(copte.getUDF11());  // 供应链采购单号

        coptcPlus.setUdf51(copte.getUDF51());
        coptcPlus.setUdf52(copte.getUDF53());
        coptcPlus.setUdf53(copte.getUDF55());
        coptcPlus.setUdf04(copte.getTE047());
        List<Attach> fileList = fileService.fileList(new FileListDto(db, dh, "COPI06", YmlConfig.getYFCOMPANY()));
        List<String> urls = new ArrayList<>();
        for(int i = 0; i < fileList.size(); i++) {
            String docId = fileList.get(i).getDocid();
            String fileName = fileList.get(i).getFilename();
            String url = "/files/" + docId.substring(3, 6) + "000" +
                    "/" + docId + "/" + fileName;
            urls.add(url);
        }
        List<Coptd> coptdPlusList = coptdMapper.getCoptdPlusList(db, dh);
        for(Coptd coptd : coptdPlusList) {   // 新增的不会出现在这里
            Coptf coptfCp = null;
            for(Coptf coptf : coptfList) {
                if((coptf.getTF054().trim().equals("2") || coptf.getTF054().trim().equals("3")) && coptf.getTF104().trim().equals(coptd.getTd003().trim())) {
                    coptfCp = coptf;
                    break;
                }
            }
            if(coptfCp == null) continue;
            coptd.setChangeType(coptfCp.getTF054());
            coptd.setChangeReason(coptfCp.getTF018());
            coptd.setModiDate(coptfCp.getMODI_DATE());
            coptd.setModifier(coptfCp.getMODIFIER());
            coptd.setTd004(coptfCp.getTF005());
            coptd.setTd005(coptfCp.getTF006());
            coptd.setTd006(coptfCp.getTF007());
            coptd.setTd007(coptfCp.getTF008());
            coptd.setTd008(coptfCp.getTF009());
            coptd.setTd010(coptfCp.getTF010());
            coptd.setTd011(coptfCp.getTF013());
            coptd.setTd012(coptfCp.getTF014());
            coptd.setTd013(coptfCp.getTF015());
            coptd.setTd014(coptfCp.getTF016());
            coptd.setTd015(coptfCp.getTF036());
            coptd.setTd020(coptfCp.getTF033());
            coptd.setTd022(coptfCp.getTF011());
            coptd.setTd023(coptfCp.getTF012());
            coptd.setTd024(coptfCp.getTF020());
            coptd.setTd026(coptfCp.getTF021());
            coptd.setTd027(coptfCp.getTF022());
            coptd.setTd029(coptfCp.getTF023());
            coptd.setTd030(coptfCp.getTF024());
            coptd.setTd031(coptfCp.getTF025());
            coptd.setTd032(coptfCp.getTF026());
            coptd.setTd034(coptfCp.getTF027());
            coptd.setTd036(coptfCp.getTF028());
            coptd.setTd037(coptfCp.getTF029());
            coptd.setTd038(coptfCp.getTF030());
            coptd.setTd039(coptfCp.getTF031());
            coptd.setTdi01(coptfCp.getTFI01());
            coptd.setTdi02(coptfCp.getTFI02());
            coptd.setTdi03(coptfCp.getTFI03());
            coptd.setTd061(coptfCp.getTF042());
            coptd.setTd062(coptfCp.getTF043());
            coptd.setUdf03(coptfCp.getUDF06());  // 生管确认日
            coptd.setUdf04(coptfCp.getUDF02());  // 客户品名
            coptd.setUdf05(coptfCp.getUDF04());  // 客户品号规格

            coptd.setUdf51(coptfCp.getUDF51());  // 总金额(六位数)
            coptd.setUdf52(coptfCp.getUDF53());
            coptd.setUdf53(coptfCp.getUDF55());
            coptd.setUdf54(coptfCp.getUDF57());
            coptd.setUdf55(coptfCp.getUDF59());
            coptd.setUdf56(coptfCp.getUDF61());
            if(coptfCp.getTF054().equals("3")) coptd.setTd016(coptfCp.getTF017());

            Coptd dd = coptdMapper.coptfCoptdPlus(coptd.getTd007(), coptd.getTd004());
            coptd.setMC002(dd.getMC002());
            coptd.setMb064(dd.getMb064());
        }

        for(Coptf coptf : coptfList) {     // 变更单中新增的
            if(coptf.getTF054().equals("1")) {
                Coptd coptd = new Coptd();
                coptd.setChangeType("1");
                coptd.setChangeReason(coptf.getTF018());
                coptd.setCreator(coptf.getCREATOR());
                coptd.setTd001(db); coptd.setTd002(dh); coptd.setTd003(coptf.getTF104());
                coptd.setTd004(coptf.getTF005());
                coptd.setTd005(coptf.getTF006());
                coptd.setTd006(coptf.getTF007());
                coptd.setTd007(coptf.getTF008());
                coptd.setTd008(coptf.getTF009());
                coptd.setTd010(coptf.getTF010());
                coptd.setTd011(coptf.getTF013());
                coptd.setTd012(coptf.getTF014());
                coptd.setTd013(coptf.getTF015());
                coptd.setTd014(coptf.getTF016());
                coptd.setTd015(coptf.getTF036());
                coptd.setTd016("N");
                coptd.setTd020(coptf.getTF033());
                coptd.setTd022(coptf.getTF011());
                coptd.setTd023(coptf.getTF012());
                coptd.setTd024(coptf.getTF020());
                coptd.setTd026(coptf.getTF021());
                coptd.setTd027(coptf.getTF022());
                coptd.setTd029(coptf.getTF023());
                coptd.setTd030(coptf.getTF024());
                coptd.setTd031(coptf.getTF025());
                coptd.setTd032(coptf.getTF026());
                coptd.setTd034(coptf.getTF027());
                coptd.setTd036(coptf.getTF028());
                coptd.setTd037(coptf.getTF029());
                coptd.setTd038(coptf.getTF030());
                coptd.setTd039(coptf.getTF031());
                coptd.setTdi01(coptf.getTFI01());
                coptd.setTdi02(coptf.getTFI02());
                coptd.setTdi03(coptf.getTFI03());
                coptd.setTd061(coptf.getTF042());
                coptd.setTd062(coptf.getTF043());
                coptd.setUdf03(coptf.getUDF06());  // 生管确认日
                coptd.setUdf04(coptf.getUDF02());  // 客户品名
                coptd.setUdf05(coptf.getUDF04());  // 客户品号规格
                // coptd.setUdf51(coptfCp.getTF144());  // 总金额(六位数)
                coptd.setUdf51(coptf.getUDF51());  // 总金额(六位数)
                coptd.setUdf52(coptf.getUDF53());
                coptd.setUdf53(coptf.getUDF55());
                coptd.setUdf54(coptf.getUDF57());
                coptd.setUdf55(coptf.getUDF59());
                coptd.setUdf56(coptf.getUDF61());

                Coptd dd = coptdMapper.coptfCoptdPlus(coptd.getTd007(), coptd.getTd004());
                coptd.setMC002(dd.getMC002());
                coptd.setMb064(dd.getMb064());

                coptd.setApchnum(0D);
                coptd.setSjchnum(0D);
                coptd.setThnum(0D);
                coptd.setBhnum(0D);
                coptdPlusList.add(coptd);
            }
        }

        BigDecimal tc029 = new BigDecimal(0);
        BigDecimal tc030 = new BigDecimal(0);
        BigDecimal tc031 = new BigDecimal(0);
        BigDecimal tci03 = new BigDecimal(0);
        BigDecimal tci04 = new BigDecimal(0);
        BigDecimal udf51 = new BigDecimal(0);
        BigDecimal udf52 = new BigDecimal(0);
        BigDecimal udf53 = new BigDecimal(0);
        for(Coptd coptd : coptdPlusList) {
            tc029 = tc029.add(new BigDecimal(coptd.getTd038().toString()));
            tc030 = tc030.add(new BigDecimal(coptd.getTd039().toString()));
            tci03 = tci03.add(new BigDecimal(coptd.getTdi01().toString()));
            tci04 = tci04.add(new BigDecimal(coptd.getTdi02().toString()));
            tc031 = tc031.add(new BigDecimal(coptd.getTd008().toString()));
            udf51 = udf51.add(new BigDecimal(coptd.getUdf51().toString()));
            udf52 = udf52.add(new BigDecimal(coptd.getUdf52().toString()));
            udf53 = udf53.add(new BigDecimal(coptd.getUdf53().toString()));
        }
        coptcPlus.setTc029(tc029.doubleValue());  // 税前金额
        coptcPlus.setTc030(tc030.doubleValue());  // 税额
        coptcPlus.setTc031(tc031.doubleValue());   // 数量
        coptcPlus.setTci03(tci03.doubleValue());  // 本币税前金额
        coptcPlus.setTci04(tci04.doubleValue());  // 本币税额
        coptcPlus.setUdf51(udf51.doubleValue());  // 总金额（六位数的）
        coptcPlus.setUdf52(udf52.doubleValue());  // 自定义税前金额（六位数的）
        coptcPlus.setUdf53(udf53.doubleValue());  // 自定义税额（四位数的）

        if(!coptdPlusList.isEmpty()){
            coptdPlusList.stream().forEach(arr -> {
                arr.setTd012(arr.getUdf51());
                if (arr.getMg005()==null||arr.getMg005().equals("")){
                    List<Copmg> copmgs = copmgMapper.selectList(new LambdaQueryWrapper<Copmg>()
                            .eq(Copmg::getMg001, coptcPlus.getTc004()).eq(Copmg::getMg003, arr.getTd014()).eq(Copmg::getMg002,arr.getTd004()));
                    if (!copmgs.isEmpty()){
                        arr.setMg005(copmgs.get(0).getMg005());
                        arr.setMg006(copmgs.get(0).getMg006());
                    }
                }
                Double td010Double = this.coptdMapper.getTd010Double(coptcPlus.getTc004(), arr.getTd004());
                if (td010Double!=null){
                    if (arr.getTd011()>td010Double){
                        arr.setHistoricalunitprice(2);
                    }else if (arr.getTd011().equals(td010Double)){
                        arr.setHistoricalunitprice(1);
                    }else {
                        arr.setHistoricalunitprice(0);
                    }
                }
            });
        }

        CoptcVo coptcVo =new CoptcVo();
        coptcVo.setCoptc(coptcPlus);
        coptcVo.setCoptdList(coptdPlusList);
        coptcVo.setUrls(urls);
        return Result.success(coptcVo);
    }

    @Log("上报销售变更单")
    @ApiOperation("上报销售变更单")
    @GetMapping("/report")
    @DSTransactional
    public Result report(
            @RequestParam String TC001, @RequestParam String TC002, @RequestParam String TC003, @RequestParam String username, @RequestParam String leader
    ) {
        if (StringUtils.isEmpty(TC001) || StringUtils.isEmpty(TC002) || StringUtils.isEmpty(TC003)) {
            return Result.error("单别或单号或版本号为空");
        }
        if (StringUtils.isEmpty(username)) {
            return Result.error("用户名为空");
        }
        String formkey = "copte";
        String beanName = formkey + "ServiceImpl";
        ProcessInstance processInstance;
        String bussinessKey = formkey + ":" + TC001 + ":" + TC002 + ":" + TC003;
        String id = TC001 + ":" + TC002 + ":" + TC003;
        Boolean b = actFlowCommService.isOnly(bussinessKey, formkey);
        Boolean b2 = copteService.tc30IsN(TC001, TC002, TC003);
        if (b && b2) {
            processInstance = actFlowCommService.startProcess(formkey, beanName, bussinessKey, id, username, leader);
        } else {
            return Result.error("有相同单据正在审核或该单据已审核完成");
        }
        //获取流程实例id
        String processInstanceId = processInstance.getId();
        List<Task> taskList = actFlowCommService.myTaskList(username);
        if (!CollectionUtils.isEmpty(taskList)) {
            for (Task task : taskList) {
                if (task.getAssignee().equals(username) &&
                        task.getProcessInstanceId().equals(processInstanceId)) {
                    log.info("ProcessInstanceId is {}", task.getProcessInstanceId());
                    log.info("taskid is {}",task.getId());
                    actFlowCommService.completeProcess("同意", username, task.getId(),"");
                }
            }
        }
        else {
            return Result.error("空任务！");
        }
        return Result.success("上报销售变更单成功");
    }

//    @Log("销售变更单详情  掌上易飞上报")

    /**
     *
     * @param TC001 单别
     * @param TC002 单号
     * @param TC003 版本号
     * @return
     */
    @ApiOperation("销售变更单详情 掌上易飞上报  Copte 销售变更单单头 Coptf 销售变更单单身")
    @PostMapping("/queryXq")
    public Result<Map<String,Object>> queryXq(@RequestParam(defaultValue = "") String TC001,
                                              @RequestParam(defaultValue = "") String TC002,
                                              @RequestParam(defaultValue = "") String TC003){

        if (StringUtils.isEmpty(TC001) || StringUtils.isEmpty(TC002)) {
            return Result.error("单别或单号为空");
        }
        Copte copte = copteMapper.selectOne(new LambdaQueryWrapper<Copte>().eq(Copte::getTE001, TC001).eq(Copte::getTE002, TC002).eq(Copte::getTE003, TC003));
        if (copte == null) {
            return Result.error("销售变更单不存在");
        }
        List<Coptf> coptfList = this.coptfMapper.selectList(new LambdaQueryWrapper<Coptf>().eq(Coptf::getTF001, TC001).eq(Coptf::getTF002, TC002).eq(Coptf::getTF003, TC003));
        Map<String,Object> map = new HashMap<>();

        List<CoptfVo> res = new ArrayList<>();
        for(Coptf c : coptfList) {
            CoptfVo coptfVo = new CoptfVo();
            org.springframework.beans.BeanUtils.copyProperties(c, coptfVo);
            res.add(coptfVo);
        }
        map.put("copte",copte);
        map.put("coptfList",res);
        return Result.success(map);
    }

    @PostMapping("/getCurStatus")
    @ApiOperation("获得当前单据的审核状态")
    public Result getStatus(@RequestParam String TC001,@RequestParam String TC002,@RequestParam String TC003){
        String formKey="copte";
        String businessKey=formKey+":"+TC001+":"+TC002+":"+TC003;
        List<TaskInfo> curProcessState = actFlowCommService.getCurProcessState(businessKey, formKey);
        return Result.success(curProcessState);
    }
}
